package com.wandian.texas;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.PropertyConfigurator;

import com.wandian.centerserver.CenterMgr;
import com.wandian.centerserver.CenterSessionMgr;
import com.wandian.texas.db.CommonDaoManager;
import com.wandian.texas.db.DBMgr;
import com.wandian.texas.db.DaoManager;
import com.wandian.texas.db.Result;
import com.wandian.texas.entity.CornucopiaEntity;
import com.wandian.util.Config;
import com.wandian.util.DateUtil;
import com.wandian.util.Log;
import com.wandian.util.PathUtil;
import com.wandian.util.TimeWatch;

/**
 * @author long
 * @date 2012-12-5 下午5:50:49
 * @qq 108232706
 * @description 中心服务器
 */
public class CenterServer {
	private static ThreadRun callBackThread = null;

	public static void main(String[] args) {
		GameData.CONFIGPATH = PathUtil.getAasolutePath(args[0]);// String.format("%s/%s",
		if (!Config.initConfig(GameData.CONFIGPATH)) {
			System.out.println("系统配置文件加载错误，程序退出!");
			return;
		} else {
			PropertyConfigurator.configure(PathUtil.getAasolutePath(Config.getValue("log4j.path")));
			Log.debug("加载配置文件成功");
		}
		Log.info(String.format("[CenterServer]中心服务器启动中.........."));
		GameData.CENTERSTARTTIME = System.currentTimeMillis();
		try {
			if (args.length <= 0) {
				Log.error(String.format("[CenterServer]中心服务器启动错误,请输入配置文件地址路径..."));
				return;
			}
			CommonDaoManager.init(1);// 启动通用数据库
			if (!GameData.initDbConfig()) {
				Log.error("初始化系统全局的配置错误，程序退出!");
				return;
			}
			GameData.SERVER = CommonDaoManager.ServerListDao(0).find(Config.getInt("center.id"));
			if (GameData.SERVER == null) {
				throw new Exception("寻找服务器端口等配置信息失败!");
			}
			Log.info(String.format("[CenterServer]本服务器信息:%s", GameData.SERVER));
			if (DaoManager.GameRoomDao(0).executeProcedureReturn("sp_ClearServerLogin", DBMgr.TexasPokerDB) != 1) {
				throw new Exception("清除所有服务器登录失败!");
			}
			if (startUpSessionMgr())
				startCenterServer();
			CommonDaoManager.close();
		} catch (IOException e) {
			e.printStackTrace();
			Log.info(String.format("[CenterServer]运行异常:%s", e));
		} catch (Throwable e) {
			e.printStackTrace();
			Log.info(String.format("[CenterServer]运行异常:%s", e));
		}
		GameData.CENTERSTOPTIME = System.currentTimeMillis();
		Log.info(String.format("[CenterServer]中心服务器已退出,总计运行时间:%s", TimeWatch.getTime(GameData.CENTERSTOPTIME - GameData.CENTERSTARTTIME)));
	}

	private static void testInsertCornucopia() {
		ArrayList<CornucopiaEntity> Cornucopias = new ArrayList<CornucopiaEntity>();
		for (int i = 0; i < 2; i++) {
			CornucopiaEntity cornucopia = new CornucopiaEntity(1, 1, i, 4, "诸葛亮", 9, "AsKsQsJsTs");
			cornucopia.WinMoney = 10000;
			Cornucopias.add(cornucopia);
		}
		Log.info("开始同步最新的积宝日志.....");
		Result rs = new Result() {
			@Override
			public void run() {
				try {
					ArrayList<CornucopiaEntity> cornucopiaRecordList = (ArrayList<CornucopiaEntity>) this.dataList;
					CornucopiaEntity tempCornucopia;
					for (int i = 0; i < cornucopiaRecordList.size(); i++) {
						tempCornucopia = cornucopiaRecordList.get(i);
						this.prepareAddBatch(tempCornucopia.CornucopiaCallBack, tempCornucopia.CornucopiaType, tempCornucopia.IsAllow, tempCornucopia.IsUsing, tempCornucopia.IsSend, tempCornucopia.ServerId, tempCornucopia.RoomId, tempCornucopia.GameId, tempCornucopia.SeatId, tempCornucopia.UserId, tempCornucopia.NickName, tempCornucopia.WinMoney, tempCornucopia.CardType, tempCornucopia.MaxCards);
					}

				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		};
		CommonDaoManager.GameRoomDao(0).execBatchProcedure(rs, DBMgr.TexasPokerDB, "sp_AddCornucopiasRecord", 14, Cornucopias);
		if (rs.IsSuccess) {
			Log.info("同步数据成功,总共" + Cornucopias.size() + "条 ,成功同步行," + rs.RowSize);
		} else {
			Log.error("同步全数据失败");
		}
	}

	private static void startCenterServer() throws IOException {
		String mycmd;
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			while (true) {
				mycmd = br.readLine();
				try {

					if ("exit".equals(mycmd)) {
						shutDownSessionMgr();
						CenterSessionMgr.getInstance().exitThread();
						break;
					} else if ("startup".equals(mycmd)) {
						startUpSessionMgr();
					} else if ("shutdown".equals(mycmd)) {
						pauseSessionMgr();
					} else if ("cmdthread".equals(mycmd)) {
						ThreadPool.getInstance().printThreadPoolStatus();
					} else if ("testGetPagination".equals(mycmd)) {
						GameServer.testGetPagination();
					} else if ("testSelect".equals(mycmd)) {
						testSelect();
					} else if ("testTimeToUpdateCornucopia".equals(mycmd)) {
						CenterMgr.TimeToUpdateCornucopia(null);
					} else if ("testInsertCornucopia".equals(mycmd)) {
						testInsertCornucopia();
					} else if ("startAllTimer".equals(mycmd)) {
						CenterMgr.startAllTimer();
					} else if ("stopAllTimer".equals(mycmd)) {
						CenterMgr.stopAllTimer();
					} else if ("timers".equals(mycmd)) {
						CenterMgr.timersDetail();
					} else if ("execProduce".equals(mycmd)) {
						testExecProduce();
					} else if ("testSqlImage".equals(mycmd)) {
						testSqlImage();
					} else {

						Log.info(String.format("[CenterServer][%s] 命令不支持!", DateUtil.format(new Date())));
					}
				} catch (Exception e) {
					Log.info(String.format("[CenterServer][%s] 运行异常%s!", DateUtil.format(new Date()), e));
					Thread.currentThread().interrupt();
				}
				TimeUnit.MILLISECONDS.sleep(1);
			}// end while
			br.close();
		} catch (InterruptedException e) {
			Log.info(String.format("[CenterServer][%s] 运行中出现异常:%s!", DateUtil.format(new Date()), e));
		}

	}

	private static void testExecProduce() {
		ByteBuffer byteBuffer = ByteBuffer.allocate(100);
		byteBuffer.putInt(1);
		byteBuffer.putInt(2);
		byteBuffer.putInt(3);
		byteBuffer.flip();
		// ByteBuffer newBuffer=byteBuffer.slice();
		StringBuilder result = new StringBuilder();
		// ArrayList<Byte> list = new ArrayList<Byte>();
		// while(byteBuffer.remaining()>0){
		// list.add(byteBuffer.get());
		// }
		byte[] data = new byte[byteBuffer.remaining()];
		byteBuffer.get(data, 0, data.length);
		for (int i = 0; i < data.length; i++) {
			result.append(data[i] + ",");
		}
		System.out.println(result);
		// CommonDaoManager.GameRoomDao(0).executeUpdate("sp_AddPlayMoneyLog",
		// true, 1, 0, 5);
	}

	private static void testSqlImage() {
		byte[] headImage;
		try {
			FileInputStream inStream = new FileInputStream("E:/res/reels/Image/image 253.png");
			headImage = new byte[inStream.available()];
			int count = 1;
			while (count > 0) {
				count = inStream.read(headImage, 0, headImage.length);
			}
			CommonDaoManager.GameRoomDao(0).executeUpdate("sp_UpdateUserHeadImage", DBMgr.TexasPokerDB, 4, headImage);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static void testSelect() {
		Result rs = new Result() {
			@Override
			public void run() {
				try {
					if (!this.IsSuccess || this.RowSize < 1)
						return;
					this.DataRows = new Object[1][1];
					if (this.ResultSet.next()) {
						this.DataRows[0][0] = this.ResultSet.getBytes(1);
					}
					System.out.println(this);

				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		};
		CommonDaoManager.GameRoomDao(0).getSelect(rs, "PlayerInfo", "where userid=5", "HeadImage", "");
		if (rs.DataRows != null && rs.DataRows[0][0] != null) {
			byte[] imageData = (byte[]) rs.DataRows[0][0];
			FileOutputStream oStream = null;
			try {
				oStream = new FileOutputStream("E:/res/reels/Image/" + System.nanoTime() + ".png");
				oStream.write(imageData, 0, imageData.length);
				oStream.flush();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				if (oStream != null) {
					try {
						oStream.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					oStream = null;
				}
			}
		}
	}

	private static boolean startUpSessionMgr() {
		if (CenterSessionMgr.getInstance().isStarted()) {
			Log.info(String.format("[CenterServer]SessionMgr已启动!"));
			return false;
		} else {
			try {
				if (CenterSessionMgr.getInstance().start()) {
					if (callBackThread == null) {
						callBackThread = new ThreadRun(CenterSessionMgr.getInstance());
						callBackThread.setRun(true);
						callBackThread.start();
					}
					Log.info(String.format("[CenterServer][%s] SessionMgr启动成功!", DateUtil.format(new Date())));
					// 定时去推送积宝,30秒更新一次
					CenterMgr.startAllTimer();
					callBackThread.status = 0;
					return true;
				} else {
					CenterSessionMgr.getInstance().stop(true);
					Log.info(String.format("[CenterServer][%s] SessionMgr启动失败!", DateUtil.format(new Date())));
				}
			} catch (Throwable e) {
				e.printStackTrace();
				Log.info(String.format("[CenterServer][%s] SessionMgr启动异常:%s!", DateUtil.format(new Date()), e));
			}
		}
		return false;
	}

	private static void shutDownSessionMgr() {
		// 正常命令
		// 停止定时去推送积宝,30秒更新一次
		CenterMgr.stopAllTimer();
		if (!CenterSessionMgr.getInstance().isStarted()) {
			Log.info(String.format("[CenterServer][%s] SessionMgr未启动!", DateUtil.format(new Date())));
		} else {
			if (CenterSessionMgr.getInstance().isStarted()) {
				CenterSessionMgr.getInstance().stop(true);
				Log.info(String.format("[CenterServer][%s]游戏服务器SessionMgr已停止", DateUtil.format(new Date())));
			}
		}
		callBackThread.setRun(false);
	}

	private static void pauseSessionMgr() {
		// 正常命令
		if (callBackThread == null)
			return;
		callBackThread.status = 1;
		if (!CenterSessionMgr.getInstance().isStarted()) {
			Log.info(String.format("[CenterServer][%s] SessionMgr未启动!", DateUtil.format(new Date())));
		} else {
			if (CenterSessionMgr.getInstance().isStarted()) {
				CenterSessionMgr.getInstance().stop(false);
				Log.info(String.format("[CenterServer][%s]游戏服务器SessionMgr已暂停", DateUtil.format(new Date())));
			}
		}
	}

	public static boolean initComponent(boolean initResult, String componentName) {
		if (!initResult)
			Log.error(componentName + "错误");
		else {
			Log.info(componentName + "加载完成");
		}
		return initResult;
	}
}
